package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.enums.ProductEnum;
import com.wing.common.model.entity.ExternalProduct;
import com.wing.common.model.response.ExternalProductVO;
import com.wing.common.service.ExternalProductService;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.model.request.ProductReviewAddForm;

import com.wing.product.model.request.ProductReviewAuditForm;
import com.wing.product.model.response.ProductReviewSearchVo;
import com.wing.product.model.response.ReviewDetailVo;
import com.wing.product.service.ProductUnitService;
import com.wing.sell.model.response.OrderReviewNeedVo;
import com.wing.sell.service.OrderProReviewService;

import com.wing.sell.service.OrderProService;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-28 16:27
 **/
@Slf4j
@Validated
@Api(value = "Admin-评审管理", tags = "#/product/productReview")
@RestController("productReviewController")
@RequestMapping("product/admin/productReview")
@RequiredArgsConstructor
public class ProductReviewController {

    @Autowired
    private OrderProReviewService orderProReviewService;

    @Autowired
    private ProductUnitService productUnitService;

    @Autowired
    private OrderProService orderProService;

    @Autowired
    private ExternalProductService externalProductService;

    @Value("${review.engineering.processId}")
    private String processId;
 
    @ApiOperation(value = "查询评审任务列表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "processId", value = "评审性质(必填)", defaultValue = "1", example = "1", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductReviewSearchVo> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            , String reviewPostId
            , String productTypeId
            , String orderStatus
            , String customerId
            , String customerSku
            , String orderId
    ) {

        Page<ProductReviewSearchVo> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        params.put("reviewPostId", reviewPostId);
        params.put("productTypeId", productTypeId);
        params.put("orderStatus", orderStatus);
        params.put("customerId", customerId);
        params.put("customerSku", customerSku);
        params.put("orderId", orderId);
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);
        Page<ProductReviewSearchVo> list = orderProReviewService.getReviewPageBy(pg, params, processId);
        list.getRecords().forEach(
                info -> {
                    info.setStatusName(ProductEnum.ReviewEmum.getNameByCode(info.getStatus()));
                    //如果订单id不为空 则从订单中 拿数据
                    if (null != info.getOrderId()) {
                        OrderReviewNeedVo needVo = orderProService.selectReviewNeedInfoBy(info.getOrderId(), info.getProId());
                        BeanUtil.copyProperties(needVo, info,false);
                    }
                }
        );
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    /**
     * 添加评审任务
     *1
     * @param productReviewAddForm
     * @return 1
     */
    @ApiOperation(value = "添加评审任务", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductReviewAddForm.class) ProductReviewAddForm productReviewAddForm) {
        if (orderProReviewService.addReviewInfoBy(productReviewAddForm) > 0) {
            return JsonResult.success("添加任务成功");
        }
        return JsonResult.fail("添加任务失败");
    }

    @ApiOperation(value = "添加评审任务(外部)", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addReviewInfoByOut")
    public JsonResult addReviewInfoByOut(@RequestBody @Validated(ProductReviewAddForm.class) ProductReviewAddForm productReviewAddForm) {
        if (orderProReviewService.addReviewInfoBy(productReviewAddForm) > 0) {
            return JsonResult.success("添加任务成功");
        }
        return JsonResult.fail("添加任务失败");
    }


    /**
     * 评审任务详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "评审任务详情", notes = "查看")
    @GetMapping("/detail/{id}")
    public JsonResult rewiewDetail(@PathVariable("id") String id) {
        ReviewDetailVo reviewDetailVo = orderProReviewService.getReviewDetailBy(id);
        if (ObjectUtil.isNotEmpty(reviewDetailVo) && null != reviewDetailVo.getOrderId()){
            OrderReviewNeedVo needVo = orderProService.selectReviewNeedInfoBy(reviewDetailVo.getOrderId(), reviewDetailVo.getProId());
                        BeanUtil.copyProperties(needVo, reviewDetailVo,false);
                        reviewDetailVo.setCusProductCategory(needVo.getProductTypeName());
                        reviewDetailVo.setCusProductName(needVo.getCustomerSkuName());
                        reviewDetailVo.setCusProductSpec(needVo.getCusSkuSpec());

                        //查询外部产品信息
            ExternalProductVO byId = externalProductService.getNeedInfoBy(needVo.getCusProductId());
            if (ObjectUtil.isNotEmpty(byId)) {
                reviewDetailVo.setRemark(byId.getPackInstructions());
                reviewDetailVo.setFileName(byId.getFileName());
                reviewDetailVo.setAttachmentPdfUrl(byId.getFileUrl());
            }

        }
        if (reviewDetailVo == null) {
            return JsonResult.fail("获取详情失败！");
        }
        //是否关联新产品
        if (StrUtil.isNotEmpty(reviewDetailVo.getIsUseOrAdd())) {
            reviewDetailVo.setIsUseOrAdd(ProductEnum.ReviewUseOrNewEmum.getNameByCode(reviewDetailVo.getIsUseOrAdd()));
        }
        //赋值结果
        if (StrUtil.isNotEmpty(reviewDetailVo.getResult())) {
            reviewDetailVo.setResult(ProductEnum.ReviewResultEmum.getNameByCode(reviewDetailVo.getResult()));
        }

        if (reviewDetailVo.getProductTypeId() != null) {
            QueryWrapper<ProductUnitInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("type", 0);
            wrapper.eq("product_type", reviewDetailVo.getProductTypeId());
            wrapper.eq("data_source_type", ProductUnitInfo.DataSourceType.enterprise.getValue());
            wrapper.eq("is_base_unit", "1");
            ProductUnitInfo productUnitInfo = productUnitService.getOne(wrapper);
            //赋值基础单位
            if (ObjectUtil.isNotEmpty(productUnitInfo)){
                reviewDetailVo.setInUnitName(productUnitInfo.getName());
            }
        }
        return JsonResult.success("获取成功！", reviewDetailVo);
    }


    @ApiOperation(value = "待评审任务审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "审核id", defaultValue = "", example = "1", required = false, dataType = "Long", paramType = "query")
            , @ApiImplicitParam(name = "result", value = "审核状态", defaultValue = "1:审核通过,2:驳回", example = "1", required = false, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "reviewDesc", value = "审核备注", defaultValue = "", example = "1", required = false, dataType = "String", paramType = "query")
    })
    @PostMapping("/link")
    public JsonResult link(@Validated(ProductReviewAuditForm.class) ProductReviewAuditForm productReviewAuditForm) {
        try {
            return orderProReviewService.linkInfo(productReviewAuditForm);
        } catch (Exception e) {
            log.error("link fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "审核id", defaultValue = "", example = "1", required = false, dataType = "Long", paramType = "query")
            , @ApiImplicitParam(name = "result", value = "审核状态", defaultValue = "1:审核通过,2:驳回", example = "1", required = false, dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "reviewDesc", value = "审核备注", defaultValue = "", example = "1", required = false, dataType = "String", paramType = "query")
    })
    @PostMapping("/auditInfoBy")
    public JsonResult auditInfoBy(@Validated(ProductReviewAuditForm.class) ProductReviewAuditForm productReviewAuditForm) {
        try {
            return orderProReviewService.auditInfoBy(productReviewAuditForm);
        } catch (Exception e) {
            log.error("audit fail", e);
            return JsonResult.fail(e.getMessage());
        }
    }

}